package com.example.book.sys.user.controller;

import com.example.book.base.BaseController;
import com.example.book.common.utils.Constants;
import com.example.book.base.Result;
import com.example.book.common.utils.RedisService;
import com.example.book.common.shiro.ShiroUtils;
import com.example.book.domain.sys.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录控制器
 *
 * @author haocj
 */
@Controller
@RequestMapping("/sys")
public class LoginController extends BaseController {


    @Autowired
    private RedisService redisService;


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(SysUser sysUser) {
        Subject subject = ShiroUtils.getSubjct();
        String password = new Sha256Hash(sysUser.getPassword()).toHex();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getLoginName(), password);
        try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            return Result.error(Constants.ERROR, uae.getMessage());
        }catch (IncorrectCredentialsException ice){
            return Result.error(Constants.ERROR, ice.getMessage());
        }catch (DisabledAccountException dae){
            return Result.error(Constants.RESTRICTED_LOGIN, dae.getMessage());
        }
        return Result.success(Constants.SUCCESS_MSG);
    }
}
